package cn.com.dingtek.genius.manager.server.service;

import cn.com.dingtek.genius.manager.server.repository.db.entity.CompanyBase;
import cn.com.dingtek.genius.manager.server.repository.db.entity.CompanyPush;
import cn.com.dingtek.genius.manager.server.repository.db.manager.CompanyBaseManager;
import cn.com.dingtek.genius.manager.server.repository.db.manager.CompanyPushManager;
import cn.com.dingtek.genius.manager.server.repository.db.manager.UserBaseManager;
import cn.com.dingtek.genius.manager.server.utils.MybatisPlusUtil;
import cn.com.dingtek.genius.manager.server.utils.Verify;
import cn.com.dingtek.genius.manager.server.utils.VerifyException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CompanyService {
    @Autowired
    private CompanyBaseManager companyBaseManager;
    @Autowired
    private CompanyPushManager companyPushManager;

    public IPage<CompanyBase> list(CompanyBase param, int currentPage, int pageSize) {
        QueryWrapper<CompanyBase> query = Wrappers.emptyWrapper();
        if (param != null) {
            query = MybatisPlusUtil.customLikeQuery(null, "company_name", param.getCompanyName());
            query = MybatisPlusUtil.customEqQuery(query, "company_account", param.getCompanyAccount());
            query = MybatisPlusUtil.customEqQuery(query, "mobile", param.getMobile());
            query = MybatisPlusUtil.customEqQuery(query, "postal_code", param.getPostalCode());
        }

        return companyBaseManager.page(new Page<CompanyBase>(currentPage, pageSize).setAsc("id"), query);
    }

    public void add(CompanyBase param, Date now) {
        String passwdHash = DigestUtils.md5DigestAsHex(param.getPasswd().getBytes(StandardCharsets.UTF_8));

        try {
            Verify.isTrue(companyBaseManager.save(CompanyBase.builder()
                    .companyAccount(param.getCompanyAccount())
                    .companyName(param.getCompanyName())
                    .passwd(passwdHash)
                    .mobile(param.getMobile())
                    .postalCode(param.getPostalCode())
                    .address(param.getAddress())
                    .remarks(param.getRemarks())
                    .ctime(now)
                    .utime(now)
                    .version(0).build()), "新增公司失败。");
        } catch (DuplicateKeyException e) {
            throw new VerifyException("该公司名已存在。");
        }
    }

    public CompanyBase info(Long id) {
        Verify.isTrue(id != null && id > 0, "公司不存在");
        CompanyBase companyBase = companyBaseManager.getById(id);
        companyBase.setPasswd(null);
        return companyBase;
    }

    public void update(CompanyBase param, Date now) {
        Verify.isTrue(param.getId() != null && param.getId() > 0, "公司不存在");

        CompanyBase companyBase = companyBaseManager.getById(param.getId());
        Verify.notNull(companyBase, "公司不存在");

        String passwdHash = null;
        if (param.getPasswd() != null) {
            passwdHash = DigestUtils.md5DigestAsHex(param.getPasswd().getBytes(StandardCharsets.UTF_8));
        }

        CompanyBase toUpdate = CompanyBase.builder()
                .id(param.getId())
                .companyName(param.getCompanyName())
                .mobile(param.getMobile())
                .postalCode(param.getPostalCode())
                .address(param.getAddress())
                .remarks(param.getRemarks())
                .utime(now)
                .version(companyBase.getVersion())
                .build();

        if (passwdHash != null) {
            toUpdate.setPasswd(passwdHash);
        }

        Verify.isTrue(companyBaseManager.updateById(toUpdate), "更新公司失败");
    }

    public void remove(Long id) {
        if (id == null || id <= 0) {
            return;
        }
        companyBaseManager.removeById(id);
    }

    public List<JSONObject> options(Long currentUserId) {
//        UserBase userBase = userBaseManager.getById(currentUserId);
//        if (userBase.getAuthGroupId() != 1) {
//            CompanyBase companyBase = companyBaseManager.getById(userBase.getCompanyId());
//            return Arrays.asList(new JSONObject().fluentPut("id", companyBase.getId()).fluentPut("companyName", companyBase.getCompanyName()));
//        }

        List<CompanyBase> companyBaseList = companyBaseManager.list();
        return companyBaseList.stream()
                .map(item -> new JSONObject()
                        .fluentPut("id", item.getId())
                        .fluentPut("companyName", item.getCompanyName()))
                .collect(Collectors.toList());

    }

    public JSONObject pushInfo(Long id) {
        CompanyBase companyBase = companyBaseManager.getById(id);
        Verify.notNull(companyBase, "公司不存在");
        CompanyPush companyPush = companyPushManager.getByCompanyId(id);

        JSONObject result = new JSONObject().fluentPut("companyId", id)
                .fluentPut("companyName", companyBase.getCompanyName());

        if (companyPush != null) {
            result.fluentPut("pushUrl", companyPush.getPushUrl())
                    .fluentPut("deviceType", companyPush.getDeviceType());
        }

        return result;
    }

    public void pushInfoUpdate(CompanyPush param, Date now) {
        CompanyPush companyPush = companyPushManager.getByCompanyId(param.getCompanyId());
        if (companyPush == null) {
            companyPushManager.save(CompanyPush.builder()
                    .companyId(param.getCompanyId())
                    .pushUrl(param.getPushUrl())
                    .deviceType(param.getDeviceType())
                    .ctime(now)
                    .utime(now)
                    .version(0)
                    .build());
        } else {
            companyPushManager.updateById(CompanyPush.builder()
                    .id(companyPush.getId())
                    .pushUrl(param.getPushUrl())
                    .deviceType(param.getDeviceType())
                    .utime(now)
                    .version(companyPush.getVersion())
                    .build());
        }
    }

}
